const connections = require('../app/database');
const dbService = require('./dbService');

const momentColumns = `
                        m.id id,
                        m.content content,
                        m.images images,
                        m.create_time create_time,
                        m.modify_time modify_time
                    `;
const userColumns =
  "JSON_OBJECT('id', u.id, 'name', u.name, 'sex', u.sex, 'age', u.age, 'phone_num', u.phone_num, 'avatar', u.avatar)";

class MomentService {
  async getMomentDetailById(id) {
    const SQL = `SELECT ${momentColumns}, ${userColumns} user
        FROM
            moment AS m
            JOIN users AS u ON m.user_id = u.id 
        WHERE
            m.id = 1`;
    const result = await connections.query(SQL, [id]);
    return result[0];
  }
  async getMomentList(params) {
    const { pageSize, pageNum, userId } = params;
    let totalSQL = 'SELECT * FROM moment';
    if (userId) {
      totalSQL += ` WHERE user_id = ${userId}`;
    }
    const SQL = `SELECT ${momentColumns}, ${userColumns} user, 
      (SELECT COUNT(*) FROM comment WHERE moment_id = m.id) commentCount
      FROM
        moment AS m
        JOIN users AS u ON m.user_id = u.id
        ${userId ? ` WHERE u.id = ${userId} ` : ''}
        ORDER BY m.create_time DESC
        LIMIT ?, ?`;
    const offset = pageSize * (pageNum - 1);
    const limit = Number(pageSize);
    const [resp1, resp2] = await Promise.all([connections.query(totalSQL), connections.query(SQL, [offset, limit])]);
    const total = resp1[0].length;
    const moments = resp2[0];
    return {
      moments,
      total,
    };
  }

  async queryAndCreateLabels(labels) {
    const dbLabels = [];
    for (let item of labels) {
      const label = await dbService.query({ name: item }, 'label');
      if (label && label.length) {
        dbLabels.push(label[0]);
      } else {
        const result = await dbService.insert({ name: item }, 'label');
        if (result && result.insertId) {
          dbLabels.push({ id: result.insertId, name: item });
        }
      }
    }
    return dbLabels;
  }
}

module.exports = new MomentService();
